package com.example.administrator.fishbone.bean;

import android.util.SparseArray;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Created by ${杨文超} on 2016/8/30.
 */
public class ViewHolder implements View.OnClickListener{
    private SparseArray<View> mViews = new SparseArray<>();
    private View mCovertView;
    private int mPostion;
    private OnClickBack mOnClickBack;
    public ViewHolder(View covertView, OnClickBack onClickBack) {
        mCovertView = covertView;
        if (covertView != null) {
            mCovertView.setTag(this);
        }
        mOnClickBack = onClickBack;
    }
    private <T extends View> T findView(int viewId) {
        View view = null;
        if (mCovertView != null) {
            view = mCovertView.findViewById(viewId);
        }
        if (view != null) {
            mViews.put(viewId, view);
        }
        return (T) view;
    }
    public <T extends View> T getView(int viewId) {
        View view = mViews.get(viewId); //先根据ViewId去mViews中拿取
        if (view != null) {//如果拿到的为null则代表mViews中没有
            return (T) view; //不为空就返回拿取到的View
        }
        view = findView(viewId);//为空走这一步，去调用findView方法然后返回查找到的View
        return (T) view;
    }

    public ViewHolder setText(int viewId, CharSequence text) {
        TextView view = getView(viewId);
        if (view != null) {
            view.setText(text);
        }
        return this;
    }

    public ViewHolder setTextViewPic(int viewId, int picId) {
        TextView view = getView(viewId);
        if (view != null) {
            view.setCompoundDrawablesWithIntrinsicBounds(picId, 0, 0, 0);
        }
        return this;
    }

    public ViewHolder setPic(int viewId, int picId) {
        ImageView view = getView(viewId);
        if (view != null) {
            view.setImageResource(picId);
        }
        return this;
    }

    public ViewHolder setOnClickListener(int viewId) {
        View view = getView(viewId);
        if (view != null) {
            view.setOnClickListener(this);
        }
        return this;
    }

    @Override
    public void onClick(View v) {
        mOnClickBack.onClickBack(mPostion, v, this);
    }


    public int getPosition() {
        return mPostion;
    }

    public void setPosition(int position) {
        mPostion = position;
    }
}
